package com.l024.framework.manager;

import com.l024.framework.utils.Logutils;
import com.l024.framework.utils.SHA1;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
* @Author  wu_ming_zhi_bei
* @Date   2020/3/9 11:40
* @Notes  请求管理类
*/
public class HttpManger {
    private static final String TOKEN_URL = "http://api-cn.ronghub.com/user/getToken.json";
    private static final String CLOUD_SECRET = "GBnF9N5BXb2L";
    private static final String CLOUD_KEY = "lmxuhwagleu7d";
    private static volatile HttpManger httpManger;
    private OkHttpClient okHttpClient;
    private HttpManger(){
        okHttpClient = new OkHttpClient();
    }

    public static HttpManger getInstance(){
        if(httpManger == null){
            synchronized (HttpManger.class){
                if(httpManger==null){
                    httpManger = new HttpManger();
                }
            }
        }
        return httpManger;
    }

    /**
     * 请求融云获取token
     */
    public String postCloudToken(HashMap<String,String> map){
        //参数
        String Timestamp = String.valueOf(System.currentTimeMillis()/1000);
        String Nonce = String.valueOf(Math.floor(Math.random()*100000));
        String Signature = SHA1.sha1(CLOUD_SECRET+Nonce+Timestamp);
        FormBody.Builder builder = new FormBody.Builder();
        for(String key:map.keySet()){
            builder.add(key,map.get(key));
            Logutils.i("key:"+map.get(key));
        }
        RequestBody requestBody = builder.build();
        //添加签名规则
        Request request = new Request.Builder()
                .url(TOKEN_URL)
                .addHeader("Timestamp",Timestamp)
                .addHeader("App-Key",CLOUD_KEY)
                .addHeader("Nonce",Nonce)
                .addHeader("Signature",Signature)
                .addHeader("Content-Type","application/x-www-form-urlencoded")
                .post(requestBody)
                .build();
        try {
            String body = okHttpClient.newCall(request).execute().body().string();
            return body;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
